from fdfs_client.client import Fdfs_client
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response

from apps.goods.models import SPU, Brand, GoodsCategory
from apps.meiduo_admin.serializers.spus import SPUSerializer, BrandSerializer,GoodsCategorySerializer
from apps.meiduo_admin.utils import PageNum


class SPUView(ModelViewSet):
    '''
    list:获取用户
    create:保存用户
    '''
    # 指定序列化器
    serializer_class = SPUSerializer
    # 指定查询集
    queryset = SPU.objects.all()
    #指定分页器
    pagination_class = PageNum

    #获取品牌信息
    def brands(self,request):
        # 1.获取所以品牌
        data = Brand.objects.all()
        # 2.返回所有品牌
        ser = BrandSerializer(data,many=True)
        return Response(ser.data)

    # 获取一级分类
    def channel(self,request):
        #1: 查询一级分类
        data = GoodsCategory.objects.filter(parent=None)
        #2: 2.返回分类信息
        ser=GoodsCategorySerializer(data,many=True)
        return Response(ser.data)


    # 获取二级分类
    def channel2(self,request,pk):
        #1: 查询一级分类
        data = GoodsCategory.objects.filter(parent_id=pk)
        #2: 2.返回分类信息
        ser=GoodsCategorySerializer(data,many=True)
        return Response(ser.data)


    ######## 额外定义一个保存spu详情图片信息

    def images(self,request):

        # 1.获取前端传递的图片数据
        image=request.data.get("image")
        # 2.链接fadtDFS
        clinet=Fdfs_client("/home/python/Desktop/meiduo/meiduo_46/meiduo_mall/utils/fastdfs/client.conf")

        # 3.上传图片
        res=clinet.upload_by_buffer(image.read())
        # 4.判断上传是否成功
        if res["Status"] != "Upload successed.":
            return Response({"error":"上传失败"},status=400)
        # 5.提取链接地址
        path = res.get("Remote file_id")
        image_url="http://image.meiduo.site:8888/"+path
        return Response({"img_url":image_url})
